package com.icesoft.icefaces.security;

import job.manager.db.ec.UsersEB;
import job.manager.db.sb.UserBean;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
 

public class UserDetailsServiceImpl implements UserDetailsService {
    private UserBean ub;

    public UserDetailsServiceImpl(UserBean ub) {
        this.ub=ub;
    }

    public UserDetails loadUserByUsername(String username )
            throws UsernameNotFoundException, DataAccessException {
        UsersEB user= ub.findUser(username);
        if (user == null)
            throw new UsernameNotFoundException("User not found: " + username);
        else {
            return makeUser(user);
        }
    }

    private org.springframework.security.userdetails.User makeUser(UsersEB user) {
        return new org.springframework.security.userdetails.User(user.getUserName(), user
                .getPassword(), true, true, true, true,
                makeGrantedAuthorities(user));
    }

    private GrantedAuthority[] makeGrantedAuthorities(UsersEB user) {
        GrantedAuthority[] result = new GrantedAuthority[1];
        
        result[0]=new GrantedAuthorityImpl(user.getUsergroup().getGroupName());
        return result;
    }

}
